package com.hornsun.repository;

import com.hornsun.domain.dbo.User;
import com.hornsun.domain.dbo.UserExample;
import com.hornsun.repository.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.hornsun.util.DESEncryption.DATA_BASE;

/**
 * Created by 编译中... on 2018/1/5.
 */
@Repository
public class UserRepository {
    @Autowired
    private UserMapper userMapper;

    public long getCountByUsernameAndPassword(String username,String password){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andNameEqualTo(username).andPasswordEqualTo(password);
        return userMapper.countByExample(userExample);
    }

    public void insertUser(User user){
        user.setUsername(DATA_BASE.encrypt(user.getUsername()));
        user.setPassword(DATA_BASE.encrypt(user.getPassword()));
        user.setMobile(DATA_BASE.encrypt(user.getMobile()));
        if (userMapper.insertSelective(user)!=1){
            throw new IllegalArgumentException("insert user failed ");
        }

    }

    public void updateUser(User user){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(user.getMobile()!=null){
            user.setMobile(DATA_BASE.encrypt(user.getMobile()));
        }
        criteria.andUserGuidEqualTo(user.getUserGuid());
        userMapper.updateByExample(user,userExample);
    }

    public int deleteUser(String userName){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andNameLike(userName);
        return userMapper.deleteByExample(userExample);
    }

    public List<User> getAllAccount(){
        List<User>  list=userMapper.selectByExample(new UserExample());
        for (User user :list){
            user.setUsername(DATA_BASE.decrypt(user.getUsername()));
            user.setMobile(DATA_BASE.decrypt(user.getMobile()));
            user.setPassword(DATA_BASE.decrypt(user.getPassword()));
        }
        return list;
    }
    public User getUserByUsername(String username){
        return userMapper.selectByUsername(username);
    }


}
